#include "maper.h"

LuaMaper::LuaMaper(int c800, int c600)
{
	_800 = c800;
	_600 = c600;
}

LuaMaper::~LuaMaper()
{
	if (_map != nullptr)
	{
		cMaper::getInstance()->freeMap(_mapid);
	}
}

ELuna::LuaTable LuaMaper::load(const char* path, int mapid)
{
	ELuna::LuaTable t(L);
	if (mapid != _mapid)
	{
		cMaper::getInstance()->freeMap(_mapid);
		_map = cMaper::getInstance()->getMap(path, mapid, true);
		_mapid = mapid;
	}
	if (_map != nullptr)
	{
		t.set("mw", _map->mw);
		t.set("mh", _map->mh);
		t.set("bw", _map->bw);
		t.set("bh", _map->bh);
	}
	return t;
}

bool LuaMaper::isObstacle(int x, int y)
{
	if (_map == nullptr)
	{
		return true;
	}
	return _map->isObstacle(x, _map->mh / 20 - 1 - y);
}

ELuna::LuaTable LuaMaper::search(int x, int y, int tx, int ty)
{
	ELuna::LuaTable t(L);
	if (_map == nullptr)
	{
		return t;
	}
	std::vector<Vec2> vs;
	_map->search(x, y, tx, ty, vs);
	if (vs.empty())
	{
		return t;
	}

	for(int k = 1, size = vs.size(); k < size; ++k)
	{
		ELuna::LuaTable xy(L);
		const auto& v = vs[k];
		xy.set("x", v.x);
		xy.set("y", v.y);
		t.set(size - k - 1, xy);
	}
	return t;
}

void LuaMaper::step(int cx, int cy)
{
	if (_map != nullptr)
	{
		_map->step(cx, cy);
	}
}

void LuaMaper::render(/*int cx, int cy*/)
{
	if (_map != nullptr)
	{
		_map->render(/*Block(cx, cy, _800, _600*/);
	}
}

void LuaMaper::renderAlpha(/*int cx, int cy*/)
{
	if (_map != nullptr)
	{
		_map->renderAlpha(/*cx, cy, _800, _600*/);
	}
}


int REG_GGE_Maper(lua_State * L){
	const char* gname = "__ggeMaper";
	ELuna::registerClass<LuaMaper>(L, gname,  ELuna::constructor<LuaMaper,int,int>);

	ELuna::registerMethod<LuaMaper>(L, "load", &LuaMaper::load);
	ELuna::registerMethod<LuaMaper>(L, "isObstacle", &LuaMaper::isObstacle);
	ELuna::registerMethod<LuaMaper>(L, "search", &LuaMaper::search);
	ELuna::registerMethod<LuaMaper>(L, "step", &LuaMaper::step);
	ELuna::registerMethod<LuaMaper>(L, "render", &LuaMaper::render);
	ELuna::registerMethod<LuaMaper>(L, "renderAlpha", &LuaMaper::renderAlpha);

	lua_getglobal(L, gname);
	lua_pushnil(L);
	lua_setglobal(L,gname);
	return 1;
}

